package com.vehicle.controller;

import com.vehicle.service.FaceRecognitionService;
import com.vehicle.service.DriverUserService;
import com.vehicle.common.Result;
import com.vehicle.entity.DriverUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 人脸注册控制器
 * 处理司机人脸注册相关的请求
 */
@RestController
@RequestMapping("/api/face/register")
public class FaceRegisterController {

    private static final Logger logger = LoggerFactory.getLogger(FaceRegisterController.class);

    @Autowired
    private FaceRecognitionService faceRecognitionService;

    @Autowired
    private DriverUserService driverUserService;

    /**
     * 上传人脸照片并注册
     * @param file 人脸照片文件
     * @param driverUser 司机信息
     * @return 注册结果
     */
    @PostMapping("/upload")
    public Result<?> registerFace(@RequestParam("file") MultipartFile file, DriverUser driverUser) {
        try {
            logger.info("开始人脸注册，司机姓名：{}", driverUser.getDriverName());

            // 1. 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error(400, "人脸照片不能为空");
            }

            // 2. 检测人脸并获取faceToken
            String faceToken = faceRecognitionService.faceDetect(file);
            if (faceToken == null) {
                return Result.error(400, "人脸检测失败，无法识别有效的人脸");
            }

            // 3. 设置人脸token
            driverUser.setFaceToken(faceToken);

            // 4. 保存司机人脸信息
            driverUserService.save(driverUser);

            logger.info("人脸注册成功，司机姓名：{}", driverUser.getDriverName());
            return Result.success("人脸注册成功");
        } catch (Exception e) {
            logger.error("人脸注册失败", e);
            return Result.error(500, "人脸注册失败：" + e.getMessage());
        }
    }

    /**
     * 批量获取人脸认证token
     * @return token结果
     */
    @GetMapping("/getToken")
    public Result<?> getAuthToken() {
        try {
            String token = faceRecognitionService.getAuthToken();
            return Result.success(token);
        } catch (Exception e) {
            logger.error("获取认证token失败", e);
            return Result.error(500, "获取认证token失败：" + e.getMessage());
        }
    }

    /**
     * 检测人脸（用于前端预览）
     * @param file 人脸照片文件
     * @return 检测结果
     */
    @PostMapping("/detect")
    public Result<?> detectFace(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error(400, "人脸照片不能为空");
            }

            String faceToken = faceRecognitionService.faceDetect(file);
            if (faceToken == null) {
                return Result.error(400, "人脸检测失败");
            }

            return Result.success("人脸检测成功");
        } catch (Exception e) {
            logger.error("人脸检测失败", e);
            return Result.error(500, "人脸检测失败：" + e.getMessage());
        }
    }
}